#include "stdafx.h"
#include "..\headers\GameObjectManager.h"
#include "..\headers\LuaGameObject.h"

namespace ne{

GameObjectManager::GameObjectManager(void){}
GameObjectManager::~GameObjectManager(void){}

void GameObjectManager::Update(){
	if (!m_addList.empty()){
		for (unsigned int i=0;i<m_addList.size();i++){
			m_gameObjects.push_front(m_addList[i]);
		}
		for(unsigned int i=0;i<m_addList.size();i++){
			m_addList[i]->onInit();	// we run onInit after objects has been added because they may search for other game objects in the gameObect List upon initialization
		}
		m_addList.clear();
	}
	if (!m_gameObjects.empty()){
		for(auto it=m_gameObjects.begin();it!=m_gameObjects.end();it++){
			(*it)->onUpdate();
		}
	}
	if (!m_removeList.empty()){
		for (unsigned int i=0;i<m_removeList.size();i++){
			m_gameObjects.remove(m_removeList[i]);
			m_removeList[i]->Remove();
		}
		m_removeList.clear();
	}
}

void GameObjectManager::UpdateSimulation(){
	if (!m_gameObjects.empty()){
		for(auto it=m_gameObjects.begin();it!=m_gameObjects.end();it++){
			(*it)->onSimulation();
		}
	}
}

bool GameObjectManager::AddGameObject(LuaGameObject* luaObject){
	if(luaObject!=nullptr){
		m_addList.push_back(luaObject);
		luaObject->onStartup();
		return true;
	}
	return false;
}

bool GameObjectManager::RemoveGameObject(LuaGameObject* luaObject){
	if (luaObject!=nullptr){
		if (!luaObject->GetRemove()){
			m_removeList.push_back(luaObject);
			luaObject->SetRemove(true);
			return true;
		}
	}
	return false;
}

void GameObjectManager::Shut(){
	if (!m_removeList.empty()){
		for (unsigned int i=0;i<m_removeList.size();i++){
			m_gameObjects.remove(m_removeList[i]);
			m_removeList[i]->Remove();
		}
		m_removeList.clear();
	}
	if (!m_addList.empty()){
		for (unsigned int i=0;i<m_addList.size();i++){
			m_addList[i]->Remove();
		}
		m_addList.clear();
	}
	if (!m_gameObjects.empty()){
		for (auto it=m_gameObjects.begin();it!=m_gameObjects.end();it++){
			(*it)->Remove();
		}
		m_gameObjects.clear();
	}
}

}